package com.jxpanda.starter.config.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;

/**
 * @author Panda
 */
@SuppressWarnings("NullableProblems")
public class JsonMessageConverter extends AbstractHttpMessageConverter<Object> {

    private final ObjectMapper jackson;

    public JsonMessageConverter(ObjectMapper jackson) {
        super(MediaType.APPLICATION_JSON);
        this.jackson = jackson;
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return jackson.readValue(inputMessage.getBody(), clazz);
    }

    @Override
    protected void writeInternal(Object serializable, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        outputMessage.getBody().write(jackson.writeValueAsBytes(serializable));
    }

}
